// pages/home/home.js
import points from '../../assets/json/points.js';
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

Page({
  data: {
    points: points,
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    user: {
      avatar: defaultAvatarUrl,
      name: "",
    },
    hasUserInfo: false
  },

  onLoad(options) {
    const user = wx.getStorageSync('user');
    if (user) {
      this.setData({
        user: user,
        hasUserInfo: true
      });
    }
  },

  // 新增：处理头像点击事件
  handleAvatarClick() {
    if (this.data.hasUserInfo) {
      // 已登录状态，执行退出登录
      this.logout();
    } else {
      // 未登录状态，跳转到个人中心
      this.navigateToMe();
    }
  },

  // 新增：退出登录方法
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('user');
          this.setData({
            user: {
              avatar: defaultAvatarUrl,
              name: ""
            },
            hasUserInfo: false
          });
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  submit() {
    const { user } = this.data;
    
    if (!user.name || user.name.trim() === "") {
      wx.showToast({
        title: '请输入昵称！',
        icon: 'none'
      });
      return;
    }

    wx.setStorageSync('user', user);
    this.setData({
      hasUserInfo: true
    });

    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      "user.avatar": avatarUrl
    });
  },

  onInputChange(e) {
    const nickName = e.detail.value;
    this.setData({
      "user.name": nickName
    });
  },

  navigateToMap() {
    wx.navigateTo({
      url: "../../pages/map/map"
    });
  },

  navigateToMe() {
    wx.navigateTo({
      url: "../../pages/me/me"
    });
  },

  navigateToMoment() {
    wx.navigateTo({
      url: "../../pages/moment/moment"
    });
  },

  scan() {
    wx.scanCode({
      success: (res) => {
        wx.navigateTo({
          url: '../../pages/point/point?id=' + res.result
        });
      }
    });
  }
});